<?php
// 引入头部
require_once 'includes/header.php';

// 检查权限 - 只有管理员可以访问
if (!$current_user || $current_user['role'] !== 'admin') {
    header('Location: /POS/index.php');
    exit;
}

// 处理操作
$action = $_GET['action'] ?? '';
$category_id = $_GET['id'] ?? 0;

// 处理分类添加
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $action === 'add') {
    $name = $_POST['name'] ?? '';
    $sort = isset($_POST['sort']) ? intval($_POST['sort']) : 0;
    
    // 验证分类名称是否已存在
    $check_sql = "SELECT id FROM categories WHERE name = ?";
    $existing_category = Database::fetch($check_sql, [$name]);
    
    if ($existing_category) {
        $_SESSION['alert'] = [
            'type' => 'danger',
            'message' => '该分类名称已存在'
        ];
    } else {
        // 插入新分类
        $sql = "INSERT INTO categories (name, sort, created_at) 
                VALUES (?, ?, NOW())";
        $result = Database::query($sql, [$name, $sort]);
        
        if ($result) {
            $_SESSION['alert'] = [
                'type' => 'success',
                'message' => '分类添加成功'
            ];
        } else {
            $_SESSION['alert'] = [
                'type' => 'danger',
                'message' => '分类添加失败'
            ];
        }
    }
    
    // 重定向到分类列表
    header('Location: /POS/categories.php');
    exit;
}

// 处理分类编辑
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $action === 'edit' && $category_id) {
    $name = $_POST['name'] ?? '';
    $sort = isset($_POST['sort']) ? intval($_POST['sort']) : 0;
    
    // 检查分类名称是否被其他分类使用
    $check_sql = "SELECT id FROM categories WHERE name = ? AND id != ?";
    $existing_category = Database::fetch($check_sql, [$name, $category_id]);
    
    if ($existing_category) {
        $_SESSION['alert'] = [
            'type' => 'danger',
            'message' => '该分类名称已被其他分类使用'
        ];
    } else {
        // 更新分类信息
        $sql = "UPDATE categories SET name = ?, sort = ? WHERE id = ?";
        $result = Database::query($sql, [$name, $sort, $category_id]);
        
        if ($result) {
            $_SESSION['alert'] = [
                'type' => 'success',
                'message' => '分类信息更新成功'
            ];
        } else {
            $_SESSION['alert'] = [
                'type' => 'danger',
                'message' => '分类信息更新失败'
            ];
        }
    }
    
    // 重定向到分类列表
    header('Location: /POS/categories.php');
    exit;
}

// 处理分类删除
if ($action === 'delete' && $category_id) {
    // 检查分类是否有关联商品
    $check_sql = "SELECT COUNT(*) FROM products WHERE category_id = ?";
    $product_count = Database::fetchColumn($check_sql, [$category_id]);
    
    if ($product_count > 0) {
        $_SESSION['alert'] = [
            'type' => 'danger',
            'message' => '该分类下有关联商品，无法删除'
        ];
    } else {
        // 删除分类
        $sql = "DELETE FROM categories WHERE id = ?";
        $result = Database::query($sql, [$category_id]);
        
        if ($result) {
            $_SESSION['alert'] = [
                'type' => 'success',
                'message' => '分类删除成功'
            ];
        } else {
            $_SESSION['alert'] = [
                'type' => 'danger',
                'message' => '分类删除失败'
            ];
        }
    }
    
    // 重定向到分类列表
    header('Location: /POS/categories.php');
    exit;
}

// 查询单个分类信息（用于编辑）
$category = null;
if ($action === 'edit' && $category_id) {
    $sql = "SELECT * FROM categories WHERE id = ?";
    $category = Database::fetch($sql, [$category_id]);
    
    if (!$category) {
        $_SESSION['alert'] = [
            'type' => 'danger',
            'message' => '分类不存在'
        ];
        header('Location: /POS/categories.php');
        exit;
    }
}

// 获取分类列表
$search = $_GET['search'] ?? '';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = 10;
$offset = ($page - 1) * $per_page;

// 构建查询条件
$where = [];
$params = [];

if ($search) {
    $where[] = "(name LIKE ?)";
    $params[] = "%$search%";
}

$where_clause = !empty($where) ? "WHERE " . implode(" AND ", $where) : "";

// 查询分类总数
$count_sql = "SELECT COUNT(*) FROM categories $where_clause";
$total = Database::fetchColumn($count_sql, $params);
$total_pages = ceil($total / $per_page);

// 查询分类列表
$sql = "SELECT c.*, 
        (SELECT COUNT(*) FROM products WHERE category_id = c.id) as product_count 
        FROM categories c 
        $where_clause 
        ORDER BY c.sort ASC, c.name ASC 
        LIMIT $offset, $per_page";
$categories = Database::fetchAll($sql, $params);
?>

<div class="container-fluid">
    <div class="row mb-4">
        <div class="col-md-6">
            <h1 class="h3 mb-0">分类管理</h1>
            <p class="text-muted">查看和管理所有商品分类</p>
        </div>
        <div class="col-md-6 text-md-right">
            <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#addCategoryModal">
                <i class="fas fa-plus-circle"></i> 添加分类
            </button>
        </div>
    </div>
    
    <!-- 搜索栏 -->
    <div class="card mb-4">
        <div class="card-body">
            <form action="" method="GET" class="row">
                <div class="col-md-8 mb-3 mb-md-0">
                    <div class="input-group">
                        <div class="input-group-prepend">
                            <span class="input-group-text"><i class="fas fa-search"></i></span>
                        </div>
                        <input type="text" class="form-control" name="search" placeholder="分类名称" value="<?php echo htmlspecialchars($search); ?>">
                    </div>
                </div>
                <div class="col-md-2">
                    <button type="submit" class="btn btn-primary btn-block">搜索</button>
                </div>
                <div class="col-md-2">
                    <a href="/POS/categories.php" class="btn btn-secondary btn-block">重置</a>
                </div>
            </form>
        </div>
    </div>
    
    <!-- 分类列表 -->
    <div class="card">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-striped table-hover">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>分类名称</th>
                            <th>商品数量</th>
                            <th>排序</th>
                            <th>创建时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($categories)): ?>
                        <tr>
                            <td colspan="7" class="text-center py-4">没有找到相关分类</td>
                        </tr>
                        <?php else: ?>
                        <?php foreach ($categories as $c): ?>
                        <tr>
                            <td><?php echo $c['id']; ?></td>
                            <td><?php echo htmlspecialchars($c['name']); ?></td>
                            <td><span class="badge badge-info"><?php echo $c['product_count']; ?></span></td>
                            <td><?php echo $c['sort']; ?></td>
                            <td><?php echo date('Y-m-d H:i', strtotime($c['created_at'])); ?></td>
                            <td>
                                <div class="btn-group btn-group-sm">
                                    <a href="/POS/categories.php?action=edit&id=<?php echo $c['id']; ?>" class="btn btn-primary">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <a href="#" onclick="confirmDelete(<?php echo $c['id']; ?>, <?php echo $c['product_count']; ?>); return false;" class="btn btn-danger">
                                        <i class="fas fa-trash"></i>
                                    </a>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
            
            <!-- 分页 -->
            <?php if ($total_pages > 1): ?>
            <nav aria-label="Page navigation" class="mt-4">
                <ul class="pagination justify-content-center">
                    <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                        <a class="page-link" href="?page=<?php echo $page - 1; ?>&search=<?php echo urlencode($search); ?>" aria-label="Previous">
                            <span aria-hidden="true">&laquo;</span>
                        </a>
                    </li>
                    <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                    <li class="page-item <?php echo $page == $i ? 'active' : ''; ?>">
                        <a class="page-link" href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>"><?php echo $i; ?></a>
                    </li>
                    <?php endfor; ?>
                    <li class="page-item <?php echo $page >= $total_pages ? 'disabled' : ''; ?>">
                        <a class="page-link" href="?page=<?php echo $page + 1; ?>&search=<?php echo urlencode($search); ?>" aria-label="Next">
                            <span aria-hidden="true">&raquo;</span>
                        </a>
                    </li>
                </ul>
            </nav>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- 添加分类模态框 -->
<div class="modal fade" id="addCategoryModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <form action="/POS/categories.php?action=add" method="POST">
                <div class="modal-header">
                    <h5 class="modal-title">添加新分类</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label>分类名称 <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" name="name" required>
                    </div>
                    <div class="form-group">
                        <label>排序</label>
                        <input type="number" class="form-control" name="sort" min="0" value="0">
                        <small class="form-text text-muted">数字越小排序越靠前</small>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">保存</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 编辑分类表单 -->
<?php if ($action === 'edit' && $category): ?>
<div class="container-fluid mt-4">
    <div class="card">
        <div class="card-header">
            <h5 class="mb-0">编辑分类信息</h5>
        </div>
        <div class="card-body">
            <form action="/POS/categories.php?action=edit&id=<?php echo $category['id']; ?>" method="POST">
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>分类名称 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="name" value="<?php echo htmlspecialchars($category['name']); ?>" required>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>排序</label>
                            <input type="number" class="form-control" name="sort" min="0" value="<?php echo htmlspecialchars($category['sort']); ?>">
                            <small class="form-text text-muted">数字越小排序越靠前</small>
                        </div>
                    </div>
                </div>
                <div class="form-group mt-3">
                    <a href="/POS/categories.php" class="btn btn-secondary">返回列表</a>
                    <button type="submit" class="btn btn-primary">保存更改</button>
                </div>
            </form>
        </div>
    </div>
</div>
<?php endif; ?>

<script>
// 删除确认
function confirmDelete(categoryId, productCount) {
    if (productCount > 0) {
        alert('该分类下有' + productCount + '个商品，无法删除');
        return;
    }
    
    if (confirm('确定要删除此分类吗？此操作不可恢复！')) {
        window.location.href = '/POS/categories.php?action=delete&id=' + categoryId;
    }
}

// 显示提示消息
document.addEventListener('DOMContentLoaded', function() {
    <?php if (isset($_SESSION['alert'])): ?>
    showAlert('<?php echo $_SESSION['alert']['message']; ?>', '<?php echo $_SESSION['alert']['type']; ?>');
    <?php unset($_SESSION['alert']); ?>
    <?php endif; ?>
});
</script>

<?php
// 引入页脚
require_once 'includes/footer.php';
?> 